/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.fspike.fastaprocessing;

import com.compomics.util.experiment.identification.SequenceFactory;
import com.compomics.util.gui.waiting.waitinghandlers.WaitingDialog;
import java.io.File;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author Kenneth
 */
public class FastaValidator {

    private final SequenceFactory factory;
    private final Set<String> sequenceSet = new HashSet<>();
    private WaitingDialog dialog;

    public FastaValidator() {
        factory = SequenceFactory.getInstance();
    }

    public FastaValidator(WaitingDialog dialog) {
        factory = SequenceFactory.getInstance();
        this.dialog = dialog;
    }

    /**
     * loads a fastafile in memory, adding to the file is checked in memory as
     * well
     *
     * @param fastaFile
     * @throws Exception
     */
    public void setFastaFile(File fastaFile) throws Exception {
        if (dialog != null) {
            dialog.appendReport("Validating generated fasta to avoid duplicates...", true, false);
        }
        factory.clearFactory();
        sequenceSet.clear();
        factory.loadFastaFile(fastaFile);
        for (String aProteinAccession : factory.getAccessions()) {
            try {
                sequenceSet.add(factory.getProtein(aProteinAccession).getSequence());
            } catch (NullPointerException e) {
                //this probably happens when an entry is made by a user while it was not yet loaded in the factory...;
            }
        }
        if (dialog != null) {
            dialog.appendReport("\t\tdone", false, true);
        }
    }

    /**
     * checks if a spike has already been added before to the fasta file
     *
     * @param spikeSequence the sequence of the spike
     * @return a boolean
     */
    public boolean hasSpike(String spikeSequence) {
        boolean hasContaminant = sequenceSet.contains(spikeSequence);
        if (!hasContaminant) {
            sequenceSet.add(spikeSequence);
        }
        return hasContaminant;
    }

}
